<!-- prettier-ignore -->
<template>
  <div class="task-detail">
    <div class="detail-title">
      <div class="left">
        <div style="display: flex;flex-direction: column">
          <div>
            <i class="el-icon-arrow-left" style="font-size: 22px;font-weight: 900;cursor:pointer" @click="goBack"></i>
            <span class="task-name">【{{rowData.name}}】地址分词</span>
          </div>
          <div v-if="rowData" class="detail-info">
            <span>创建人：{{rowData.user}}</span>
            <span>所属单位：{{rowData.unit}}</span>
            <span>创建时间：{{rowData.createTime}}</span>
            <span>范围：{{rowData.source}}</span>
          </div>
        </div>
        <!--<el-button size="large" type="text" @click="showMap">{{isMapShow ? '关闭地图' : '开启地图'}}</el-button>-->
      </div>
      <div class="right">
        <div class="card">
          <div class="card-top">
            共分词条
          </div>
          <div class="card-bottom">
            <span class="number">{{rowData ? rowData.count:''}}</span>
            条
          </div>
        </div>
        <div class="aPartition"></div>
        <div class="card">
          <div class="card-top">
            总耗时
          </div>
          <div class="card-bottom" v-html="timeConsuming">
            <!--<span class="number">{{timeConsuming}}</span>-->
            <!--分-->
          </div>
        </div>
        <div class="aPartition"></div>
        <div class="card">
          <div class="card-top">
            分词通过率
          </div>
          <div class="card-bottom">
            <span class="number">100</span>
            %
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="query-box">
        <el-input v-model="standardAddress" placeholder="统一标准地址" style="width: 300px;margin-right:10px">
          <el-button slot="append" icon="el-icon-search" type="primary" @click="detailTableQuery"></el-button>
        </el-input>
        <el-radio-group v-model="filterCriteria">
          <el-radio label="all">全部</el-radio>
          <el-radio label="adopt">分词通过</el-radio>
          <el-radio label="AI">AI修正</el-radio>
          <el-radio label="artificial">人工修正</el-radio>
          <el-radio label="toBeCorrected">待修正</el-radio>
        </el-radio-group>
      </div>
      <div class="detail-content">
        <div ref="listBox" class="list-box">
          <el-table :data="detailTable" header-row-class-name="table-header" max-height="550px"
                    row-class-name="row-class" stripe @selection-change="selectChange" @row-click="detailRowClick">
            <el-table-column :selectable="selectFun" align="center" type="selection" width="55">
            </el-table-column>
            <el-table-column align="center" fixed="left" label="序号" type="index" width="100"></el-table-column>
            <el-table-column align="center" fixed="left" label="统一标准地址" min-width="300" prop="originalAddress"></el-table-column>
            <template v-if="tableHandle">
              <el-table-column v-for="(item,index) in tableColumn" :key="index" :label="item.label" :prop="item.prop"
                               align="center" show-overflow-tooltip width="120">
                <template slot-scope="{row}">
                  <div  v-if="row.isEdit && item.prop">
                    <el-input v-model="row[item.prop]"></el-input>
                  </div>
                  <div v-else>
                    <span :style="getRowStyle(row,row[item.prop])">{{row[item.prop]}}</span>
                  </div>
                </template>
              </el-table-column>
            </template>
            <el-table-column v-if="!isMapShow" align="center" fixed="right" label="分词结果">
              <template slot-scope="{row}">
                <span v-if="row.status === '0'" style="color:red">
                  待修正
                </span>
                <span v-if="['3','4','5'].includes(row.status)" style="color:#67c23a">
                  通过
                </span>
                <span v-if="['1','2'].includes(row.status)" style="color:#e6a23c">
                  待通过
                </span>
              </template>
            </el-table-column>
            <el-table-column v-if="!isMapShow" align="center" fixed="right" label="修正方式">
              <template slot-scope="{row}">
                <span v-if="row.status === '3'">

                </span>
                <span v-if="row.status === '4'" style="color:red">
                  人工
                </span>
                <span v-if="row.status === '5' || row.status === '2'|| row.status === '1'">
                  AI
                </span>
              </template>
            </el-table-column>
            <el-table-column v-if="!isMapShow" align="center" fixed="right" label="操作" width="100">
              <template slot-scope="{row,$index}">
                <el-button v-if="!row.isEdit" type="text" @click="editThis($index)">人工修正</el-button>
                <el-button v-if="row.isEdit" style="color:green" type="text" @click="confirmThis($index)">保存</el-button>
                <el-button v-if="row.isEdit" style="color:green" type="text" @click="confirmThis($index)">恢复</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div style="display: flex;justify-content: space-between;margin-top:10px">
            <div>
              <el-button type="primary" @click="throughAI">通过AI修正结果</el-button>
              <el-button type="primary">人工修正</el-button>
            </div>
            <el-pagination :page-size="detailParams.size" :total="total" background layout="total,prev, pager, next"
                           @current-change="pageChange"></el-pagination>
          </div>

          <!--展示选中项的详情-->
          <div v-if="!tableHandle && clickDetail">
            <p>地址分词详情</p>
            <wp-scrollbar :maxHeight="210" scrollbarColor="rgba(51, 51, 51, 0.3)">
              <el-descriptions :column="1" border >
                <template v-for="(value,key) in clickDetail">
                  <el-descriptions-item  v-if="dictionaryTable[key]" :key="key" :label="dictionaryTable[key]">{{value}}</el-descriptions-item>
                </template>
              </el-descriptions>
            </wp-scrollbar>
          </div>
        </div>
        <div v-if="!tableHandle" class="map-box">
          <cesium-map @mapFinish="mapReady"></cesium-map>
          <div ref="isAiBox" style="width: 30px;height:30px;background:#f00;display: none;position: absolute;cursor:pointer"></div>
          <div ref="notAiBox" style="width: 30px;height:30px;background:green;display: none;position: absolute;cursor:pointer"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

import cesiumMap from "@/components/cesiumMap/index.vue";
import { addOverlay, removePopup } from "@/utils/map";
export default {
  name: "taskDetail",
  props: {
    rowData: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      standardAddress:'',
      filterCriteria:'all',
      total: 8,
      listWidth: "100%",
      isMapShow: false,
      tableColumn: [
        {
          label: "省",
          prop: "shengmc",
        },
        {
          label: "市",
          prop: "shimc",
        },
        {
          label: "县（区）",
          prop: "qumc",
        },
        {
          label: "街道（乡镇）",
          prop: "jdmc",
        },
        {
          label: "社区",
          prop: "sqmc",
        },
        {
          label: "街路巷",
          prop: "dlmc",
        },
        {
          label: "门牌号",
          prop:'mph'
        },
        {
          label: "小区",
          prop:'xqmc'
        },
        {
          label: "建筑物",
          prop:'jzw'
        },
        {
          label: "楼牌号",
          prop:'ldmc'
        },
        {
          label: "单元",
          prop:'dyh'
        },
        {
          label: "楼层",
          prop:'floor'
        },
        {
          label: "户室",
          prop:'fjhm'
        },
      ],
      tableHandle: true,
      queryHandle: true,
      detailTable: [],
      clickDetail: null,
      dictionaryTable: {
        standard: "统一标准地址",
        sheng: "省",
        shi: "市",
        xian: "县（区）",
        jiedao: "街道（乡镇）",
        shequ: "社区",
        zhuanshu: "专属区域",
        cunmin: "村民小组",
        zirancun: "自然村",
        jielu: "街路巷",
        isAi: "AI补充",
        lon: "经度",
        lat: "纬度",
      },
      detailParams:{
        originalAddress:'',
        id: '',
        page:1,
        size: 10
      },
      allSelection:[]
    };
  },
  computed:{
    timeConsuming(){
      const {days, hours, minutes, seconds} = this.calculateDuration(this.rowData.createTime,this.rowData.updateTime)
      let timeHtml = ''
      if (days){
        timeHtml += `<span class="number">${days}</span> 天`
      }
      if (hours){
        timeHtml += `<span class="number">${hours}</span> 时`
      }
      if (minutes){
        timeHtml += `<span class="number">${minutes}</span> 分`
      }
      timeHtml += `<span class="number">${seconds}</span> 秒`
      return timeHtml
    }
  },
  created() {
    const { id } = this.$route.params;
    this.detailParams.id = id
    this.getTaskDetail();
  },
  mounted() {
    this.overlayList = [];
  },
  components: { cesiumMap },
  methods: {
    selectChange(selection){
      this.allSelection = selection
    },
    selectFun(row,index){
      return ['1','2'].includes(row.status)
    },
    getRowStyle(data,str){
      let style = {
        color:'#6e6e6e'
      }
      if (str){
        if (!data.originalAddress.includes(str)){
          style.color = 'red'
        }
      }
      return style
    },
    // 计算持续时间
    calculateDuration(startTime, endTime) {
      const startTimestamp = this.convertToTimestamp(startTime);
      const endTimestamp = this.convertToTimestamp(endTime);
      const duration = endTimestamp - startTimestamp;  // 以毫秒为单位的持续时间

      // 将持续时间转换为更易读的格式
      const seconds = Math.floor((duration / 1000) % 60);
      const minutes = Math.floor((duration / (1000 * 60)) % 60);
      const hours = Math.floor((duration / (1000 * 60 * 60)) % 24);
      const days = Math.floor(duration / (1000 * 60 * 60 * 24));

      return {
        duration, // 毫秒
        days,
        hours,
        minutes,
        seconds
      };
    },
    // 时间转为时间戳
    convertToTimestamp(dateString) {
      const [date, time] = dateString.split(' ');
      const [year, month, day] = date.split('-');
      const [hour, minute, second] = time.split(':');
      return new Date(year, month - 1, day, hour, minute, second).getTime();
    },
    // 将当前页数据的AI部分通过
    throughAI(){
      let toBeApproved = []
      if (this.allSelection.length > 0){
        this.allSelection.forEach(item=>{
          toBeApproved.push(item.id)
        })
      }
      if (toBeApproved.length === 0){
        this.$message.warning('请选择数据')
      } else {
        this.$confirm('是否通过当前页中所选择的数据','提示',{
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async ()=>{
          const ids = toBeApproved.join(',')
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          const res = await axios.post(`${window.baseUrl}/address/editAI`,{
            id:ids
          })
          this.getTaskDetail()
          loading.close();
        }).catch(()=>{

        })
      }
    },
    pageChange(pageNum){
      this.detailParams.page = pageNum
      this.getTaskDetail()
    },
    detailTableQuery(){
      this.detailParams.originalAddress = this.standardAddress
      this.detailParams.page = 1
      this.getTaskDetail()
    },
    // 获取接口
    async getTaskDetail() {
      try{
        const res = await axios.get(`${window.baseUrl}/address/task/getResult`,{
          params:this.detailParams
        });
        this.detailTable = res.data.data.records
        this.total = res.data.data.total
      } catch (err){
        console.error(err);
      }
    },
    editThis(index) {
      this.$set(this.detailTable, index, {
        ...this.detailTable[index],
        isEdit: true,
      });
    },
    confirmThis(index) {
      this.$set(this.detailTable, index, {
        ...this.detailTable[index],
        isEdit: false,
      });
    },
    // 查看详情
    detailRowClick(row) {
      if (this.isMapShow) {
        this.clickDetail = row;
        this.viewer.camera.setView({
          destination: Cesium.Cartesian3.fromDegrees(row.lon, row.lat, 5000),
        });
      }
    },
    // 返回
    goBack() {
      this.$router.go(-1);
    },
    showMap() {
      this.removeAllOverlay();
      this.isMapShow = !this.isMapShow;
      this.$refs.listBox.classList.remove("hide-map-animation");
      this.$refs.listBox.classList.remove("show-map-animation");
      if (this.isMapShow) {
        this.queryHandle = false;
        this.$refs.listBox.classList.add("show-map-animation");
        setTimeout(() => {
          this.tableHandle = false;
        }, 1000);
      } else {
        this.tableHandle = true;
        this.$refs.listBox.classList.add("hide-map-animation");
        setTimeout(() => {
          this.queryHandle = true;
        }, 1000);
      }
    },
    // 地图加载完毕，加载浮云框
    mapReady() {
      this.viewer = this.Global.viewer;
      const isAiElement = this.$refs.isAiBox;
      const notAiElement = this.$refs.notAiBox;
      this.detailTable.forEach((item) => {
        const useIsAiElement = isAiElement.cloneNode(true);
        const useNotAiElement = notAiElement.cloneNode(true);
        useIsAiElement.title = item.standard;
        useNotAiElement.title = item.standard;
        var cartographic = new Cesium.Cartographic(
          Cesium.Math.toRadians(item.lon), // 经度，转换为弧度
          Cesium.Math.toRadians(item.lat), // 纬度，转换为弧度
          0 // 高度
        );
        var cartesian =
          this.viewer.scene.globe.ellipsoid.cartographicToCartesian(
            cartographic
          );
        const overlay = addOverlay(
          this.viewer,
          item.isAi ? useIsAiElement : useNotAiElement,
          cartesian,
          -15,
          -30
        );
        overlay.show();
        this.overlayList.push(overlay);
      });
      this.viewer.camera.setView({
        destination: Cesium.Cartesian3.fromDegrees(
          this.detailTable[0].lon,
          this.detailTable[0].lat,
          5000
        ),
      });
    },
    // 移除所有浮云框
    removeAllOverlay() {
      removePopup(this.overlayList);
      this.overlayList = [];
    },
  },
};
</script>

<style lang="less" scoped>
.task-detail {
  width: 100%;
  height: 100%;
  .detail-title {
    width: 100%;
    height: 118px;
    margin-bottom: 12px;
    border-radius: 8px;
    background: url(~@/assets/images/addressSegment/detail-title-bg.png)
      no-repeat;
    background-origin: content-box;
    background-position: 50% 28%;
    background-size: 110% 110%;
    display: flex;
    .left {
      width: 65%;
      height: 100%;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 40px;
      .task-name {
        font-size: 22px;
        color: #333333;
      }
      .detail-info {
        display: flex;
        justify-content: space-around;
        margin-top: 10px;
        width: 810px;
      }
    }
    .right {
      width: 35%;
      height: 100%;
      padding: 0 40px;
      display: flex;
      align-items: center;
      justify-content: space-around;
      .aPartition {
        width: 1px;
        height: 51px;
        border: 1px solid #ffffff;
        opacity: 0.2;
      }
      .card {
        width: auto;
        height: 63px;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        &-top {
          font-size: 16px;
          color: #fff;
        }
        &-bottom {
          font-size: 16px;
          color: #fff;
          vertical-align: bottom;
          .number {
            font-size: 24px;
            font-weight: 900;
            font-style: italic;
          }
        }
      }
    }
  }
  .content{
    width: 100%;
    height: calc(100% - 130px);
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    .query-box{
      margin-bottom: 10px
    }
    .detail-content {
      display: flex;
      .list-box {
        width: 100%;
        height: 100%;
      }
      .show-map-animation {
        width: 20%;
        animation: shrink 1s;
      }
      .hide-map-animation {
        width: 100%;
        animation: expand 1s;
      }
      @keyframes expand {
        from {
          width: 20%; /* 动画开始时的宽度 */
        }
        to {
          width: 100%; /* 动画结束时的宽度 */
        }
      }
      @keyframes shrink {
        from {
          width: 100%; /* 动画开始时的宽度 */
        }
        to {
          width: 20%; /* 动画结束时的宽度 */
        }
      }
      .map-box {
        width: 80%;
        height: 100%;
        padding-left: 20px;
      }
    }
  }
}
</style>
<style>
.row-class {
  cursor: pointer;
}
.number {
  font-size: 24px;
  font-weight: 900;
  font-style: italic;
}
</style>
